<template>
  <a-card :bordered="false" :bodyStyle="{ minHeight: `${layoutContentHeight - pageHeaderHeight}px` }">
    <a-form layout="inline">
      <a-form-item :label="$t('common.name')">
        <a-input v-model.trim="queryParams.name" allowClear />
      </a-form-item>
      <a-form-item :label="$t('common.status')">
        <a-select style="width:200px" v-model="queryParams.state" placeholder="请选择">
          <a-select-option value="">{{ $t('common.all') }}</a-select-option>
          <a-select-option :value="0">{{ $t('common.offline') }}</a-select-option>
          <a-select-option :value="1">{{ $t('common.online') }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" icon="search" @click="$refs.table.refresh(true)">{{ $t('common.query') }}</a-button>
        <a-button icon="reload" style="margin-left:8px" @click="resetQuery">{{ $t('common.reset') }}</a-button>
        <a-button v-action:add type="primary" style="margin-left:8px" icon="plus" @click="handleCreate">{{
          $t('common.addNewRecord', { name: 'edge' })
        }}</a-button>
      </a-form-item>
    </a-form>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :pageSize="+pageParams.pageSize"
      :showPagination="true"
    >
      <div slot="state" slot-scope="text" class="big-dot">
        <a-badge :status="text === 1 ? 'success' : 'error'" />
        {{ $t(stateMap[text]) }}
      </div>
      <span slot="action" slot-scope="text, record" class="actionsList">
        <a v-action:edit @click="$refs.edgeForm.edit(record)">{{ $t('common.edit') }}</a>
        <a-divider v-action:delete type="vertical" />
        <a-popconfirm @confirm="handleDel(record.id)">
          <div slot="title">
            {{ $t('common.delWarning', { name: 'edge' }) }}
          </div>
          <a v-action:delete class="link-danger">{{ $t('common.delete') }}</a>
        </a-popconfirm>
      </span>
    </s-table>
    <edge-form ref="edgeForm" @ok="$refs.table.refresh()" />
  </a-card>
</template>

<script>
import { layoutMixin } from '@/utils/mixin'
import { STable } from '@/components'
import { getEdgemanagementPageList, deleteEdgemanagement } from '@/api/edgeManagement/EdgeManagementController'
import { getQueryParams } from '@/utils/util'
import EdgeForm from './modules/EdgeForm'
import websocket from '@/utils/websocket'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
let ws = null

const initialqueryParams = {
  name: '',
  state: ''
}
const stateMap = {
  0: 'common.offline',
  1: 'common.online'
}
export default {
  name: 'EdgeConfig',
  mixins: [layoutMixin],
  components: {
    STable,
    EdgeForm
  },
  data () {
    return {
      initFlag: true,
      pageParams: {
        pageNo: 1,
        pageSize: 10
      },
      queryParams: { ...initialqueryParams },
      stateMap,
      // 加载数据方法 必须为 Promise 对象
      loadData: params => {
        const pageParams = this.initFlag ? { ...params, ...this.pageParams } : { ...this.pageParams, ...params }
        return getEdgemanagementPageList({ ...pageParams, ...this.queryParams })
          .then(res => {
            this.pageParams = pageParams
            this.$router.push({
              ...this.$route,
              query: {
                ...pageParams,
                ...getQueryParams(this.queryParams)
              }
            })
            this.initFlag = false
            return res.data
          })
          .catch(() => {
            return {
              data: [],
              pageNo: 1,
              pageSize: 10,
              totalCount: 0,
              totalPage: 0
            }
          })
      },
      token: ''
    }
  },
  computed: {
    columns () {
      let colums = [
        {
          title: this.$t('common.name'),
          dataIndex: 'name',
          width: 150,
          ellipsis: true
        },
        {
          title: this.$t('common.description'),
          dataIndex: 'description',
          width: 150,
          ellipsis: true
        },
        {
          title: this.$t('edgeManagement.edgeConfig.heartbeatLink'),
          dataIndex: 'heartbeatUrl',
          width: 150,
          ellipsis: true
        },
        {
          title: this.$t('common.status'),
          dataIndex: 'state',
          width: 100,
          ellipsis: true,
          scopedSlots: {
            customRender: 'state'
          }
        },
        {
          title: this.$t('common.editor'),
          dataIndex: 'modifyBy',
          ellipsis: true,
          width: 150
        },
        {
          title: this.$t('common.modifyTime'),
          dataIndex: 'modifyDate',
          width: 200,
          customRender: date => (date ? this.$options.filters.moment(date) : '')
        }
      ]
      if (this.$auth('edit,delete', this.$route.meta.permissionId)) {
        colums = colums.concat({
          title: this.$t('common.action'),
          fixed: 'right',
          width: 200,
          scopedSlots: {
            customRender: 'action'
          }
        })
      }
      return colums
    }
  },
  created () {
    const { pageNo, pageSize, name, state } = this.$route.query
    this.pageParams = {
      pageNo: pageNo ? parseInt(pageNo) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 10
    }
    this.queryParams = {
      name,
      state: state || ''
    }
    this.token = Vue.ls.get(ACCESS_TOKEN)
    // this.initWs()
  },
  beforeDestroy () {
    // ws&&ws.close()
  },
  methods: {
    resetQuery () {
      this.queryParams = { ...initialqueryParams }
      this.pageParams = {
        pageNo: 1,
        pageSize: 10
      }
      this.initFlag = true
      this.$refs.table.refresh(true)
    },
    // 新建应用
    handleCreate () {
      this.$refs.edgeForm.add()
    },
    // 单个删除
    handleDel (ids) {
      deleteEdgemanagement({ ids }).then(res => {
        this.$message.success('操作成功')
        this.$refs.table.refresh()
      })
    },
    // 批量删除
    onBatchDel (ids) {
      this.$confirm({
        title: this.$t('common.warning'),
        content: this.$t('message.warning.batchUnbind', {
          name: 'edge'
        }),
        onOk: () => {
          this.handleDel(ids.join(','))
        }
      })
    },

    initWs () {
      if (!this.token) return
      ws = websocket(
        {
          onmessage: e => {
            if (e.data) {
              console.log(e.data)
              // if (e.data) {
              //   const data = JSON.parse(e.data)
              //   for (const d of this.$refs.table.localDataSource) {
              //     if (data.device.id === d.id) {
              //       d.status = data.device.status
              //       if (d.status === 0) {
              //         // this.$refs.table.refresh();
              //         // this.$message.success('已连接');
              //       } else if (d.status === 2) {
              //         // this.$refs.table.refresh();
              //         // this.$message.success('已断开');
              //       }
              //       break
              //     }
              //   }
              // }
            }
          }
        },
        { url: `/mos/?appType=edge&Access-Token=${this.token}` }
      )
    }
  }
}
</script>

<style lang="less" scoped>
.big-dot /deep/.ant-badge-status-dot {
  width: 12px;
  height: 12px;
  box-shadow: 0 0 4px;
  border: 1px solid #fff;
}
</style>
